package com.ailot.cloud.auth.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.ailot.cloud.auth.feign.FeignUpmsService;
import com.ailot.cloud.auth.service.JwtUserDetailsService;
import com.ailot.cloud.base.common.constants.SecurityConstant;
import com.ailot.cloud.base.common.dto.Result;
import com.ailot.cloud.base.common.enums.CommonCodeEnum;
import com.ailot.cloud.base.common.exception.LoginException;
import com.ailot.cloud.base.security.authentication.model.JwtUser;
import com.ailot.cloud.upms.common.dto.JwtUserDTO;
import com.ailot.cloud.upms.common.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户详细信息
 *
 * @author
 */
@Service
@AllArgsConstructor
public class JwtUserDetailsServiceImpl implements JwtUserDetailsService {

    private final FeignUpmsService feignUserService;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
        Result<JwtUserDTO> result = feignUserService.getInfo(username);
        if (!result.isOk()) {
            throw new LoginException(result.getMsg());
        }
        return AssembleUserDetails(result.getData());
    }

    /**
     * 手机验证码登录
     *
     * @param phone
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByPhone(String phone) {
        return null;
    }

    /**
     * 组装userDetails
     *
     * @return
     */
    private UserDetails AssembleUserDetails(JwtUserDTO jwtUserDTO) {
        SysUser sysUser = jwtUserDTO.getSysUser();
        Set<String> authsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(jwtUserDTO.getRoles())) {
            Arrays.asList(jwtUserDTO.getRoles()).forEach(id -> authsSet.add(SecurityConstant.ROLE + id));
            authsSet.addAll(Arrays.asList(jwtUserDTO.getPermissions()));
        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(authsSet.toArray(new String[0]));
        boolean enable = StrUtil.equals(sysUser.getStatus(), CommonCodeEnum.TRUE.getCode());
        return new JwtUser(sysUser.getId(), sysUser.getOrgId(), sysUser.getUsername(), sysUser.getPassword(), enable, authorities);
    }
}
